package consul

import (
	"errors"
	"fmt"
	"github.com/hashicorp/consul/api"
	"week_one/client/common/global"
)

type RegistryConsul struct {
	Host string
	Port int
}
type RegistryClient interface {
	RegisterConsul(id string, name string, tags []string) error
	FilterConsulById(name string) (map[string]*api.AgentService, error)
	Deregister(id string) error
	AgentHealthServiceByName(name string) []api.AgentServiceChecksInfo
}

func NewRegistryClient(host string, port int) RegistryClient {
	return &RegistryConsul{
		Host: host,
		Port: port,
	}
}
func (c *RegistryConsul) RegisterConsul(id string, name string, tags []string) error {
	return global.ConsulClient.Agent().ServiceRegister(&api.AgentServiceRegistration{
		ID:      id,
		Name:    name,
		Tags:    tags,
		Port:    c.Port,
		Address: c.Host,
		Check: &api.AgentServiceCheck{
			Interval: "3s",
			HTTP:     fmt.Sprintf("http://%s:%d/v1/health", c.Host, c.Port),
		},
	})
}
func (c *RegistryConsul) FilterConsulById(name string) (map[string]*api.AgentService, error) {
	return global.ConsulClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, name))
}
func (c *RegistryConsul) Deregister(id string) error {
	return global.ConsulClient.Agent().ServiceDeregister(id)
}
func (c *RegistryConsul) AgentHealthServiceByName(name string) []api.AgentServiceChecksInfo {
	name, i, err := global.ConsulClient.Agent().AgentHealthServiceByName(name)
	if err != nil {
		panic(err)
	}
	if name != "passing" {
		panic(errors.New("is not health service"))
	}
	return i
}
